<template>
  <div class="order-detail">
    <!-- 订单基本信息 -->
    <div class="detail-section">
      <div class="section-header">
        <h3>订单信息</h3>
        <div class="status-tag">
          <t-tag :theme="getStatusTheme(orderData.orderStatus)">
            {{ getOrderStatusLabel(orderData.orderStatus) }}
          </t-tag>
        </div>
      </div>
      <t-row :gutter="[16, 16]">
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">订单编号</div>
            <div class="detail-value">{{ orderData.orderNo }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">订单类型</div>
            <div class="detail-value">{{ getOrderTypeLabel(orderData.orderType) }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">下单时间</div>
            <div class="detail-value">{{ formatDate(orderData.createTime) }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">支付方式</div>
            <div class="detail-value">{{ orderData.paymentMethod ? getPaymentMethodLabel(orderData.paymentMethod) : '-' }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">支付时间</div>
            <div class="detail-value">{{ orderData.paymentTime ? formatDate(orderData.paymentTime) : '-' }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">最后更新</div>
            <div class="detail-value">{{ orderData.updateTime ? formatDate(orderData.updateTime) : '-' }}</div>
          </div>
        </t-col>
      </t-row>
    </div>
    
    <!-- 产品信息 -->
    <div class="detail-section">
      <div class="section-header">
        <h3>产品信息</h3>
      </div>
      <t-row :gutter="[16, 16]">
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">产品名称</div>
            <div class="detail-value">{{ orderData.productName }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">单价</div>
            <div class="detail-value">¥{{ formatCurrency(orderData.unitPrice) }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">数量</div>
            <div class="detail-value">{{ orderData.productQuantity }}</div>
          </div>
        </t-col>
        
        <!-- 根据订单类型显示不同的字段 -->
        <template v-if="orderData.orderType === 'activity' || orderData.orderType === 'ticket'">
          <t-col :span="8">
            <div class="detail-item">
              <div class="detail-label">使用日期</div>
              <div class="detail-value">{{ orderData.useDate || '-' }}</div>
            </div>
          </t-col>
          <t-col :span="8" v-if="orderData.useTime">
            <div class="detail-item">
              <div class="detail-label">使用时间</div>
              <div class="detail-value">{{ orderData.useTime }}</div>
            </div>
          </t-col>
        </template>
        
        <template v-if="orderData.orderType === 'hotel'">
          <t-col :span="8">
            <div class="detail-item">
              <div class="detail-label">入住日期</div>
              <div class="detail-value">{{ orderData.checkInDate || '-' }}</div>
            </div>
          </t-col>
          <t-col :span="8">
            <div class="detail-item">
              <div class="detail-label">离店日期</div>
              <div class="detail-value">{{ orderData.checkOutDate || '-' }}</div>
            </div>
          </t-col>
          <t-col :span="8">
            <div class="detail-item">
              <div class="detail-label">房间类型</div>
              <div class="detail-value">{{ orderData.roomType || '-' }}</div>
            </div>
          </t-col>
          <t-col :span="8">
            <div class="detail-item">
              <div class="detail-label">房间数量</div>
              <div class="detail-value">{{ orderData.roomCount || '-' }}</div>
            </div>
          </t-col>
        </template>
      </t-row>
    </div>
    
    <!-- 游客信息 -->
    <div class="detail-section" v-if="orderData.guests && orderData.guests.length > 0">
      <div class="section-header">
        <h3>游客信息</h3>
      </div>
      <t-table
        :data="orderData.guests"
        :columns="guestColumns"
        :pagination="{ pageSize: 5 }"
        size="small"
        bordered
      />
    </div>
    
    <!-- 联系人信息 -->
    <div class="detail-section">
      <div class="section-header">
        <h3>联系人信息</h3>
      </div>
      <t-row :gutter="[16, 16]">
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">联系人</div>
            <div class="detail-value">{{ orderData.contactName || orderData.userName }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">联系电话</div>
            <div class="detail-value">{{ orderData.contactPhone || orderData.userPhone }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">用户ID</div>
            <div class="detail-value">{{ orderData.userId }}</div>
          </div>
        </t-col>
      </t-row>
    </div>
    
    <!-- 金额信息 -->
    <div class="detail-section">
      <div class="section-header">
        <h3>金额信息</h3>
      </div>
      <t-row :gutter="[16, 16]">
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">商品总额</div>
            <div class="detail-value">¥{{ formatCurrency(orderData.totalAmount) }}</div>
          </div>
        </t-col>
        <t-col :span="8" v-if="orderData.discountAmount">
          <div class="detail-item">
            <div class="detail-label">优惠金额</div>
            <div class="detail-value">¥{{ formatCurrency(orderData.discountAmount) }}</div>
          </div>
        </t-col>
        <t-col :span="8">
          <div class="detail-item">
            <div class="detail-label">实付金额</div>
            <div class="detail-value amount-primary">¥{{ formatCurrency(orderData.paymentAmount) }}</div>
          </div>
        </t-col>
        <t-col :span="8" v-if="orderData.refundAmount">
          <div class="detail-item">
            <div class="detail-label">退款金额</div>
            <div class="detail-value amount-danger">¥{{ formatCurrency(orderData.refundAmount) }}</div>
          </div>
        </t-col>
        <t-col :span="8" v-if="orderData.refundTime">
          <div class="detail-item">
            <div class="detail-label">退款时间</div>
            <div class="detail-value">{{ formatDate(orderData.refundTime) }}</div>
          </div>
        </t-col>
      </t-row>
    </div>
    
    <!-- 订单备注 -->
    <div class="detail-section">
      <div class="section-header">
        <h3>订单备注</h3>
        <t-button theme="primary" variant="text" @click="handleEditRemark">
          <template #icon><t-icon name="edit" /></template>
          编辑
        </t-button>
      </div>
      <div class="remark-content">
        {{ orderData.remark || '无备注' }}
      </div>
    </div>
    
    <!-- 状态变更记录（这里是一个示例，实际可能需要从后端获取） -->
    <div class="detail-section" v-if="orderData.orderStatus === 'cancelled' || orderData.orderStatus === 'refunding' || orderData.orderStatus === 'refunded'">
      <div class="section-header">
        <h3>状态变更信息</h3>
      </div>
      <div class="status-info">
        <div v-if="orderData.cancelReason" class="status-reason">
          <div class="reason-label">取消原因：</div>
          <div class="reason-content">{{ orderData.cancelReason }}</div>
        </div>
        <div v-if="orderData.refundReason" class="status-reason">
          <div class="reason-label">退款原因：</div>
          <div class="reason-content">{{ orderData.refundReason }}</div>
        </div>
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="detail-actions">
      <t-space>
        <t-button theme="default" @click="handleClose">关闭</t-button>
        
        <!-- 根据订单状态显示不同的操作按钮 -->
        <template v-if="orderData.orderStatus === 'paid'">
          <t-button theme="primary" @click="handleConfirmOrder">确认订单</t-button>
          <t-button theme="danger" @click="handleCancelOrder">取消订单</t-button>
          <t-button @click="handleRefundOrder">申请退款</t-button>
        </template>
        
        <template v-if="orderData.orderStatus === 'confirmed'">
          <t-button theme="primary" @click="handleCompleteOrder">完成订单</t-button>
          <t-button @click="handleRefundOrder">申请退款</t-button>
        </template>
        
        <template v-if="orderData.orderStatus === 'pending'">
          <t-button theme="danger" @click="handleCancelOrder">取消订单</t-button>
        </template>
      </t-space>
    </div>
    
    <!-- 编辑备注对话框 -->
    <t-dialog
      v-model:visible="remarkVisible"
      header="编辑备注"
      width="500px"
      :footer="false"
    >
      <t-form :data="remarkForm" @submit="handleRemarkSubmit">
        <t-form-item label="订单备注" name="remark">
          <t-textarea
            v-model="remarkForm.remark"
            placeholder="请输入订单备注"
            :autosize="{ minRows: 3, maxRows: 8 }"
          />
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="remarkVisible = false">取消</t-button>
            <t-button theme="primary" type="submit" :loading="submitLoading">保存</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
    
    <!-- 取消订单对话框 -->
    <t-dialog
      v-model:visible="cancelVisible"
      header="取消订单"
      width="500px"
      :footer="false"
    >
      <t-form :data="cancelForm" @submit="handleCancelSubmit">
        <t-form-item label="取消原因" name="reason">
          <t-textarea
            v-model="cancelForm.reason"
            placeholder="请输入取消原因"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="cancelVisible = false">取消</t-button>
            <t-button theme="danger" type="submit" :loading="submitLoading">确认取消订单</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
    
    <!-- 退款申请对话框 -->
    <t-dialog
      v-model:visible="refundVisible"
      header="申请退款"
      width="500px"
      :footer="false"
    >
      <t-form :data="refundForm" @submit="handleRefundSubmit">
        <t-form-item label="订单金额">
          <div>¥{{ formatCurrency(orderData.paymentAmount) }}</div>
        </t-form-item>
        <t-form-item label="退款金额" name="amount">
          <t-input-number
            v-model="refundForm.amount"
            :min="0"
            :max="orderData.paymentAmount"
            step="0.01"
            theme="normal"
          />
        </t-form-item>
        <t-form-item label="退款原因" name="reason">
          <t-textarea
            v-model="refundForm.reason"
            placeholder="请输入退款原因"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="refundVisible = false">取消</t-button>
            <t-button theme="primary" type="submit" :loading="submitLoading">确认退款</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import type { PrimaryTableCol } from 'tdesign-vue-next'
import {
  updateOrderStatus,
  confirmOrder,
  completeOrder,
  cancelOrder,
  requestRefund,
  updateOrderRemark,
  type Order,
  type OrderGuest,
  OrderStatus,
  OrderType,
  PaymentMethod
} from '../../../api/orders'

const props = defineProps<{
  orderData: Order
}>()

const emit = defineEmits<{
  'status-change': []
  'remark-change': []
}>()

// 游客信息表格列定义
const guestColumns: PrimaryTableCol[] = [
  { colKey: 'name', title: '姓名', width: '20%' },
  { colKey: 'idType', title: '证件类型', width: '20%' },
  { colKey: 'idNumber', title: '证件号码', width: '30%' },
  { colKey: 'phone', title: '手机号', width: '30%' }
]

// 订单类型选项
const orderTypeOptions: Record<string, string> = {
  [OrderType.TICKET]: '门票订单',
  [OrderType.HOTEL]: '酒店订单',
  [OrderType.ACTIVITY]: '活动订单',
  [OrderType.PACKAGE]: '套餐订单'
}

// 订单状态选项
const orderStatusOptions: Record<string, string> = {
  [OrderStatus.PENDING]: '待支付',
  [OrderStatus.PAID]: '已支付',
  [OrderStatus.CONFIRMED]: '已确认',
  [OrderStatus.COMPLETED]: '已完成',
  [OrderStatus.CANCELLED]: '已取消',
  [OrderStatus.REFUNDING]: '退款中',
  [OrderStatus.REFUNDED]: '已退款'
}

// 支付方式选项
const paymentMethodOptions: Record<string, string> = {
  [PaymentMethod.WECHAT]: '微信支付',
  [PaymentMethod.ALIPAY]: '支付宝',
  [PaymentMethod.BANK]: '银行卡',
  [PaymentMethod.CASH]: '现金',
  [PaymentMethod.OTHER]: '其他方式'
}

// 提交状态
const submitLoading = ref(false)

// 编辑备注
const remarkVisible = ref(false)
const remarkForm = reactive({
  remark: ''
})

// 取消订单
const cancelVisible = ref(false)
const cancelForm = reactive({
  reason: ''
})

// 申请退款
const refundVisible = ref(false)
const refundForm = reactive({
  amount: 0,
  reason: ''
})

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 格式化货币
const formatCurrency = (value: number) => {
  return value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取订单类型标签
const getOrderTypeLabel = (type: OrderType) => {
  return orderTypeOptions[type] || type
}

// 获取订单状态标签
const getOrderStatusLabel = (status: OrderStatus) => {
  return orderStatusOptions[status] || status
}

// 获取支付方式标签
const getPaymentMethodLabel = (method: PaymentMethod) => {
  return paymentMethodOptions[method] || method
}

// 获取状态对应的主题色
const getStatusTheme = (status: OrderStatus) => {
  const themeMap: Record<OrderStatus, 'default' | 'primary' | 'warning' | 'success' | 'danger'> = {
    [OrderStatus.PENDING]: 'warning',
    [OrderStatus.PAID]: 'primary',
    [OrderStatus.CONFIRMED]: 'primary',
    [OrderStatus.COMPLETED]: 'success',
    [OrderStatus.CANCELLED]: 'default',
    [OrderStatus.REFUNDING]: 'warning',
    [OrderStatus.REFUNDED]: 'default'
  }
  return themeMap[status] || 'default'
}

// 关闭详情
const handleClose = () => {
  const parentDialog = document.querySelector('.t-dialog') as HTMLElement
  if (parentDialog) {
    const closeButton = parentDialog.querySelector('.t-dialog__close') as HTMLElement
    if (closeButton) {
      closeButton.click()
    }
  }
}

// 编辑备注
const handleEditRemark = () => {
  remarkForm.remark = props.orderData.remark || ''
  remarkVisible.value = true
}

// 提交备注
const handleRemarkSubmit = async () => {
  submitLoading.value = true
  try {
    await updateOrderRemark(props.orderData.id, remarkForm.remark)
    MessagePlugin.success('备注已更新')
    remarkVisible.value = false
    emit('remark-change')
  } catch (error) {
    console.error('更新备注失败', error)
    MessagePlugin.error('更新备注失败')
  } finally {
    submitLoading.value = false
  }
}

// 确认订单
const handleConfirmOrder = async () => {
  try {
    await confirmOrder(props.orderData.id)
    MessagePlugin.success('订单已确认')
    emit('status-change')
  } catch (error) {
    console.error('确认订单失败', error)
    MessagePlugin.error('确认订单失败')
  }
}

// 完成订单
const handleCompleteOrder = async () => {
  try {
    await completeOrder(props.orderData.id)
    MessagePlugin.success('订单已完成')
    emit('status-change')
  } catch (error) {
    console.error('完成订单失败', error)
    MessagePlugin.error('完成订单失败')
  }
}

// 取消订单
const handleCancelOrder = () => {
  cancelForm.reason = ''
  cancelVisible.value = true
}

// 提交取消订单
const handleCancelSubmit = async () => {
  if (!cancelForm.reason.trim()) {
    MessagePlugin.warning('请输入取消原因')
    return
  }
  
  submitLoading.value = true
  try {
    await cancelOrder(props.orderData.id, cancelForm.reason)
    MessagePlugin.success('订单已取消')
    cancelVisible.value = false
    emit('status-change')
  } catch (error) {
    console.error('取消订单失败', error)
    MessagePlugin.error('取消订单失败')
  } finally {
    submitLoading.value = false
  }
}

// 申请退款
const handleRefundOrder = () => {
  refundForm.amount = props.orderData.paymentAmount
  refundForm.reason = ''
  refundVisible.value = true
}

// 提交退款申请
const handleRefundSubmit = async () => {
  if (refundForm.amount <= 0) {
    MessagePlugin.warning('退款金额必须大于0')
    return
  }
  if (!refundForm.reason.trim()) {
    MessagePlugin.warning('请输入退款原因')
    return
  }
  
  submitLoading.value = true
  try {
    await requestRefund(props.orderData.id, refundForm.reason, refundForm.amount)
    MessagePlugin.success('退款申请已提交')
    refundVisible.value = false
    emit('status-change')
  } catch (error) {
    console.error('申请退款失败', error)
    MessagePlugin.error('申请退款失败')
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
.order-detail {
  padding: 0 16px;
}

.detail-section {
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e7e7e7;
}

.detail-section:last-child {
  border-bottom: none;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.detail-item {
  margin-bottom: 8px;
}

.detail-label {
  font-size: 13px;
  color: rgba(0, 0, 0, 0.5);
  margin-bottom: 4px;
}

.detail-value {
  font-size: 14px;
}

.amount-primary {
  color: #0052D9;
  font-weight: 500;
}

.amount-danger {
  color: #E34D59;
  font-weight: 500;
}

.remark-content {
  background: rgba(0, 0, 0, 0.02);
  padding: 12px;
  border-radius: 4px;
  min-height: 60px;
}

.status-info {
  background: rgba(0, 0, 0, 0.02);
  padding: 12px;
  border-radius: 4px;
}

.status-reason {
  margin-bottom: 8px;
}

.status-reason:last-child {
  margin-bottom: 0;
}

.reason-label {
  font-weight: 500;
  margin-bottom: 4px;
}

.detail-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}
</style>